package sms.huawei;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import sms.ISendSmsService;
import spring.jackson.JacksonJsonUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.util.*;

@Service
@Slf4j
public class HuaWeiSendSmsServiceImpl implements ISendSmsService {

    //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    @Override
    public boolean sendSms(String phone, Map<String, Object> map) {
        /**
         * 从 Map 中获取调用华为短信接口所需要的基础配置参数
         */
        String url = MapUtil.getStr(map, "url"); //APP接入地址+接口访问URI
        String appKey = MapUtil.getStr(map, "appKey"); //APP_KEY
        String appSecret = MapUtil.getStr(map, "appSecret"); //APP_SECRET
        String sender = MapUtil.getStr(map, "sender"); //国内短信签名通道号或国际/港澳台短信通道号 国内默认为空
        String signature = MapUtil.getStr(map, "signature"); //默认签名名称 使用华为发送短信时如果不加签名名称 使用此默认名称
        String statusCallBack = MapUtil.getStr(map, "statusCallBack"); //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告

        /**
         * 华为短信模版ID 与 模版变量数组
         */
        String templateId = MapUtil.getStr(map, "templateId"); //此次调用接口发送短信的模版ID
        String[] templateVariables = MapUtil.get(map, "templateVariables", String[].class);
        return sendSms(url, appKey, appSecret, sender, signature, statusCallBack, templateId, phone, templateVariables);
    }


    public boolean sendSms(String url, String appKey, String appSecret, String sender, String signature,
                           String statusCallBack, String templateId, String phone, String[] templateVariables) {
        StringBuffer templateParasBuffer = new StringBuffer();
        if(templateVariables != null){
            templateParasBuffer.append("[");
            for (int i = 0; i < templateVariables.length; i++) {
                if(i != 0){
                    templateParasBuffer.append(",");
                }
                templateParasBuffer.append("\"").append(templateVariables[i]).append("\"");
            }
            templateParasBuffer.append("]");
        }

        String templateParas = templateParasBuffer.toString();
        String body = buildRequestBody(sender, phone, templateId, templateParas, statusCallBack, signature);
        if (null == body || body.isEmpty()) {
            log.error("body is null.");
            return false;
        }

        //请求Headers中的X-WSSE参数值
        String wsseHeader = buildWsseHeader(appKey, appSecret);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            log.error("wsse header is null.");
            return false;
        }


        //如果JDK版本低于1.8,可使用如下代码
        //CloseableHttpClient client = HttpClients.custom()
        //        .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        //            @Override
        //            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        //                return true;
        //            }
        //        }).build()).setSSLHostnameVerifier(new DefaultHostnameVerifier()).build();

        //如果JDK版本是1.8,可使用如下代码
        CloseableHttpClient client = null;
        try {
            client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(new DefaultHostnameVerifier())
                    .build();

            HttpResponse response = client.execute(RequestBuilder.create("POST")//请求方法POST
                    .setUri(url)
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());

            String responseEntity = EntityUtils.toString(response.getEntity());
            HashMap map = JacksonJsonUtil.toObject(responseEntity, HashMap.class);
            if(!Objects.equals(response.getStatusLine().getStatusCode(), 200)){
                log.error(String.format("网络请求异常！模版ID:%s, 模版签名:%s, 短信变量:%s, 返回结果:%s", templateId, signature, templateParas, responseEntity));
                return false;
            }
            if (!Objects.equals("000000", map.get("code"))){
                log.error(String.format("短信发送失败！模版ID:%s, 模版签名:%s, 短信变量:%s, 返回结果:%s", templateId, signature, templateParas, responseEntity));
                return false;
            }
            return true;
        } catch (GeneralSecurityException | IOException e) {
            log.error("短信发送失败！");
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 构造请求Body体
     */
    private static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                                           String statusCallbackUrl, String signature) {
        if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
                || templateId.isEmpty()) {
            log.error("buildRequestBody(): sender, receiver or templateId is null.");
            return null;
        }
        List<NameValuePair> keyValues = new ArrayList<>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        if (null != templateParas && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }
        if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
        }
        if (null != signature && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }

        return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
    }


    /**
     * 构造X-WSSE参数值
     */
    private static String buildWsseHeader(String appKey, String appSecret) {
        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
            log.error("buildWsseHeader(): appKey or appSecret is null.");
            return null;
        }
        String time = DateUtil.format(new Date(), "yyyy-MM-dd'T'HH:mm:ss'Z'");
        String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);

        //如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest
        //如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
        //String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8"))); //PasswordDigest
        //若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正
        //passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");

        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }

}
